import React, { useState, useEffect } from 'react'
// import { useNavigate } from "react-router-dom";
import {nanoid} from 'nanoid';
import { stuList, deleteStu ,addStu,search,updateStu} from '../../services/students'
import UpdateStu from './UpdateStu'
import AddStu from './AddStu'
import SearchStu from './SearchStu'

export default function () {
  // const navigate = useNavigate();
  const [stuArr, setStuArr] = useState([]);
  const [updateStuObj, setUpdateStuObj] = useState({});
  const [addStuObj, setAddStuObj] = useState({});

  const getStuInfo = async () => {
    let result = await stuList()
    setStuArr(result)
  }

  useEffect(() => {
    getStuInfo()
  }, [0])

  const toAdd =async (stuObj) => {
    await addStu(stuObj)
    getStuInfo()
  }

  const toDelete = async (_id) => {
    await deleteStu(_id)
    getStuInfo()
  }

  const toSearch = async (type,searchContent) => {
    let result = await search({type,searchContent})
    setStuArr(result)
  }

  const toUpdate =async (data) => {
    await updateStu(data)
    getStuInfo()
  }
  const style = { fontSize: '12px', border: '1px solid red', color: 'red' }
  const content = stuArr.map(item => (
    <tr key={nanoid()} style={{ height: '50px' }}>
      <td>{item.name}</td>
      <td>{item.age}</td>
      <td>{item.gender}</td>
      <td>
        <span style={style} onClick={() => setUpdateStuObj(item)}>更新</span>&nbsp;
        <span style={style} onClick={() => toDelete(item._id)}>删除</span>
      </td>
    </tr>
  ))

  let temp = { display: 'flex', justifyContent: 'center' }
  return (
    <div >
      <div style={temp}>
        <AddStu toAdd={toAdd}/>
      </div>
      <hr />
      <div style={temp}>
        <UpdateStu updateStuObj={updateStuObj} setUpdateStuObj={setUpdateStuObj} toUpdate={toUpdate}/>
      </div>
      <hr />
      <div style={temp}>
        <SearchStu toSearch={toSearch}/>
      </div>
      <hr />
      <table style={{ textAlign: 'center', width: '500px' }}>
        <thead>
          <tr>
            <th>姓名</th><th>年龄</th><th>性别</th><th>操作</th>
          </tr>
        </thead>
        <tbody>
          {content}
        </tbody>
      </table>

    </div>
  )

}
